package com.share.config.db;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.szeport.dyck.*.dao.view",sqlSessionTemplateRef = "viewSqlSessionTemplate")
public class ViewDataSourceConfig {
    @Primary
    @Bean(name = "viewDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.view")
    public DataSource setDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "viewSqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("viewDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/view/*.xml"));
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis.cfg.xml"));
        return bean.getObject();
    }
    @Primary
    @Bean(name = "viewSqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("viewSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    @Primary
    @Bean(name = "viewTransactionManager")
    public DataSourceTransactionManager pubTransactionManager(@Qualifier("viewDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}